import bleUtils from '../../utils/bluetooth'
import api from '../../../api/index'

Page({
	/**
   * 页面的初始数据
   */
	data: {
		bindDeviceId: null,
		devicelist: [],
		showDevice: false,
		actions: [],
		bindDevice: [],
		saveDevice: {},
		showDialog: false,
		bindDeviceTextInfo: '',
		loading: false,
		bleAvaible: true
	},

	/**
   * 生命周期函数--监听页面加载
   */
	onLoad(options) {
		this.doInitBlue()
		this.get()
  },
  // 蓝牙初始化
  doInitBlue() {
    bleUtils.initBlueTooth().then((res) => {
			this.setData({
				bleAvaible: true
			})
      this.doGetBluetoothAdapterState()
    }).catch(error => {
			this.setData({
				bleAvaible: false
			})
		})
  },
  // 获取蓝牙适配器状态
  doGetBluetoothAdapterState() {
    bleUtils.getBluetoothAdapterState()
  },
  //开始搜索蓝牙设备
  doStartSearchBlueTooth() {
    bleUtils.startSearchBlueTooth().then((res) => {
      console.log(res, '搜索设备成功')
      this.doOnBluetoothDeviceFound()
    })
  },
  // 监听搜素到新的蓝牙设备
  doOnBluetoothDeviceFound() {
    bleUtils.onBluetoothDeviceFound().then((res) => {
      console.log(res, '监听搜素到新的蓝牙设备成功')
			const filterValue = res.filter(item => item.name === 'B121053743')
			if(filterValue.length > 0) {
				const actions =  [
					{ name: filterValue[0].name, subname: filterValue[0].deviceId, deviceId: filterValue[0].deviceId },
				]
				this.setData({
					showDialog: false,
					actions: actions
				})
				// 搜索到可用的蓝牙设备，停止搜索
				bleUtils.stopSearchBlueTooth()
				this.setData({ showDevice: true });
			} else {
				//没有搜索到可用设备，重新搜索
				// console.log('没有搜索到可用设备，重新搜索')
				this.doStartSearchBlueTooth()
				this.setData({
					bindDeviceTextInfo: '没有搜索到对应的蓝牙设备，请重新搜索'
				})
				setTimeout(() => {
					this.setData({
						showDialog: false
					})
				}, 1500);
			}
    })
  },
	// 链接设备
	goBindEq() {
		if(!this.data.bleAvaible) {
			wx.showToast({
				title: '蓝牙初始化失败',
				icon: 'none',
				duration: 2000
			})
			return
		}
		this.setData({
			bindDeviceTextInfo: '正在搜索蓝牙设备'
		})
		this.setData({
			showDialog: true
		})
		this.doStartSearchBlueTooth()
	},
	onCancel() {
		this.setData({
			showDialog: false,
		})
		// 停止搜索
		bleUtils.stopSearchBlueTooth()
	},
	onClose() {
    this.setData({ showDevice: false });
  },
	onSelect(event) {
		this.setData({
			saveDevice: event.detail
		})
		const device = this.data.bindDevice.find(item => {
			return item.name === this.data.saveDevice.name
		})
		let saveDataList = []
		// 如果绑定的有该设备
		if(device) {
			wx.showToast({
				title: '该设备已绑定',
				icon: 'none',
				duration: 3000
		  })
		} else {
			const bindDevice = { name:this.data.saveDevice.name,deviceId: this.data.saveDevice.deviceId}
			saveDataList = this.data.bindDevice.concat(bindDevice)
			this.putData(saveDataList, '保存')
		}
  },
	async get() {
		this.setData({
			bindDevice: []
		})
		try {
			this.setData({
				loading: true
			})
		  const res = await api.post('/api/user/storage/get', {
			data: {
			  'key': 'devicelist'
			}
		  })
		  if(res[0].value) {
				var array = JSON.parse(res[0].value)
				const listValue = array.filter(item => item.name === 'breath')
				if(listValue.length > 0) {
					this.setData({
						bindDevice: listValue[0].devicelist
					})
				}
		  }
			this.setData({
				loading: false
			})
		} catch (e) {
		  console.log('get->', e)
		  return null
		}
	},
	delEq(e) {
		const name = e.currentTarget.dataset.name
		const data = this.data.bindDevice.filter(item => {
			return item.name !== name
		})
		this.putData(data, '删除')
	},
	putData(deviceIdList, type) {
		let num = [{name:'breath',devicelist: deviceIdList}]
		num = JSON.stringify(num)
		this.doSavedevice(num, type)
	},
	// 储存设备
	async doSavedevice(result, type) {
		try {
		  await api.post('/api/user/storage/set', {
				data: {
					'key': 'devicelist',
					'value': result
				}
				})
				wx.showToast({
					title: `${type}成功`,
					icon: 'none',
					duration: 3000
				})
				this.setData({ showDevice: false });
				this.get()
			} catch (e) {
				console.log('put->', e)
			}
	  },

	/**
   * 生命周期函数--监听页面初次渲染完成
   */
	onReady: function() {
    
	},

	/**
   * 生命周期函数--监听页面显示
   */
	onShow() {},

	/**
   * 生命周期函数--监听页面隐藏
   */
	onHide() {},

	/**
   * 生命周期函数--监听页面卸载
   */
	onUnload() {
		bleUtils.closeBluetoothAdapter()
	},

	/**
   * 页面相关事件处理函数--监听用户下拉动作
   */
	onPullDownRefresh() {},

	/**
   * 页面上拉触底事件的处理函数
   */
	onReachBottom() {},

	/**
   * 用户点击右上角分享
   */
	onShareAppMessage() {}
});
